import { onMounted, onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'

// 方法一：回调函数
export const useScroll1 = (callback) => {
  const scrollListenerHandler = () => {
    const clientHeight = document.documentElement.clientHeight // 屏幕高度
    const scrollTop = document.documentElement.scrollTop // 滚动偏移量
    const scrollHeight = document.documentElement.scrollHeight // 视图总高度
    if (clientHeight + scrollTop >= scrollHeight) {
      console.log('滚动到底部了')
      if (callback) callback()
    }
  }

  onMounted(() => {
    window.addEventListener('scroll', scrollListenerHandler)
  })

  onUnmounted(() => {
    window.removeEventListener('scroll', scrollListenerHandler)
  })
}

// 方法二：返回值
export const useScroll = (elRef) => {
  let el = window

  const isReachBottom = ref(false)
  // 屏幕高度
  const clientHeight = ref(0)
  // 滚动偏移量
  const scrollTop = ref(0)
  // 视图总高度
  const scrollHeight = ref(0)

  const scrollListenerHandler = throttle(() => {
    console.log('监听到滚动')

    if (el === window) {
      clientHeight.value = document.documentElement.clientHeight
      scrollTop.value = document.documentElement.scrollTop
      scrollHeight.value = document.documentElement.scrollHeight
    } else {
      clientHeight.value = el.clientHeight
      scrollTop.value = el.scrollTop
      scrollHeight.value = el.scrollHeight
      console.log(clientHeight.value, scrollTop.value, scrollHeight.value)
    }

    if (clientHeight.value + scrollTop.value >= scrollHeight.value - 0.5) {
      console.log('滚动到底部了')
      isReachBottom.value = true
    }
  }, 100)

  onMounted(() => {
    if (elRef) el = elRef.value
    el.addEventListener('scroll', scrollListenerHandler)
  })

  onUnmounted(() => {
    if (elRef) el = elRef.value
    el.removeEventListener('scroll', scrollListenerHandler)
  })

  return { isReachBottom, clientHeight, scrollTop, scrollHeight }
}
